import Router from "umi/router";
import {Toast} from 'antd-mobile';
import {httpUtil} from "dcloud-utils";
import {httpUrl} from "dcloud-core";
const wx = require('weixin-js-sdk')

const strlen = (str) => {
  let len = 0;
  for (let i=0; i<str.length; i++) { 
    let c = str.charCodeAt(i); 
  //单字节加1 
   if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
     len++; 
   } 
   else { 
    len+=2; 
   } 
  } 
  return len;
}

/**
 * 获取地理位置
 */
const getLocation = (callback) => {
  if(!global.wx){
    Toast.info('很抱歉，获取微信授权失败！')
  }
  Toast.loading('地理位置检测中~',0);
    wx.getLocation({
      type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        const location = res.longitude+','+res.latitude;
        // const location = '106.75,25.43';
        fetch("https://restapi.amap.com/v3/geocode/regeo?key=50bf740105378d8e4503bbb540d9ca62&location="+location).then((res)=>{
          if(res.ok){
            Toast.hide();
            res.text().then((data)=>{
              const detail=JSON.parse(data)
              let adcode = detail.regeocode ? detail.regeocode.addressComponent.adcode : '';
              if(detail.status == 1){
                // 通过 adcode判断是否在当前区域
                let regionCode = localStorage.getItem("regionCode");
                let l = strlen(regionCode);
                adcode = adcode.slice(0,l);
                if(adcode.indexOf(regionCode) != -1){
                  Toast.hide();
                  if(callback){
                    callback();
                  }
                }else{
                  Toast.info('您所在的地区暂不支持预约服务')
                }
              }else {
                Toast.offline('地理位置检测失败，请稍后重试')
              }
            })
          }else{
            Toast.offline('地理位置检测失败，请稍后重试')
          }
        }).catch((res)=>{
          Toast.offline('地理位置检测失败，请稍后重试')
        });
      },
      fail: function(res) {
        //alert(JSON.stringify(res))
        Toast.offline('地理位置检测失败，请检查是否打开地理位置授权')
      },
      cancel: function(res) {
        Toast.offline('地理位置检测失败，请允许微信使用您的地理位置');
      }
    });
}

const getOrderConfig = (callback) =>{
  if (window.location.hash.split('?')[0] == '#/login/vauth' && localStorage.getItem("tenantId")) {
    callback();
    return;
  }
  httpUtil.get(httpUrl.orderConfig, { domain: window.location.host }).then((data) => {
    if (data.code === 200) {
      localStorage.setItem("tenantId", data.data.tenantId);
      localStorage.setItem("rule", data.data.rule);
      localStorage.setItem("startDate", data.data.startDate);
      localStorage.setItem("endDate", data.data.endDate);
      localStorage.setItem("appointmentStartTime", data.data.appointmentStartTime);
      localStorage.setItem("appointmentEndTime", data.data.appointmentEndTime);
      localStorage.setItem("banners", JSON.stringify(data.data.banners));
      localStorage.setItem("ad", JSON.stringify(data.data.ad));
      localStorage.setItem("regionCode", data.data.regionCode);
     
      if(callback){
        callback()
      }
    }else{
      Toast.fail('系统错误', 2);
    }
  });
}

const getConfig = (callback) =>{
  const tenantId = localStorage.getItem("tenantId"); 
  const openId = sessionStorage.getItem("openId");
  let params = {
    tenantId: tenantId,
    url:encodeURIComponent(window.location.href.split('#')[0]),
  }
  // 这里如果没有 后台openId必须不能带这个key
  if(openId)
    params['openId'] = openId;
  
  Toast.loading('获取微信授权中...',0)
  httpUtil.get(httpUrl.config, params).then((res) => {
    if (res.code == 200) {
      wx.config({
        debug: false,
        appId: res.data.appId,
        timestamp: Number(res.data.timestamp),
        nonceStr: res.data.nonceStr,
        signature: res.data.signature.toLowerCase(),
        jsApiList: [
          'getLocation',
        ]
      });

      wx.ready(function () {
          Toast.hide();
          callback()
      })
      wx.error(function(res){
        Toast.offline('wx.error: '+JSON.stringify(res));
      });
    } else {
      Toast.fail(res.msg, 2);
    }
  }).catch(error => {
    Toast.fail('系统错误',2);
  })
}

export default {
  getLocation,
  getConfig,
  getOrderConfig
}





